﻿using System;
using System.Text;
using System.Linq;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;
using System.Windows.Controls;
using System.IO;
using System.IO.IsolatedStorage;
using System.Runtime.Serialization.Json;
using Kindohm.KSynth.Library;

namespace Kindohm.KSynth.UI
{
    public class WaveFormRepository
    {
        static WaveFormRepository instance;
        ObservableCollection<WaveFormInfo> waveForms;

        WaveFormRepository() { }

        public static WaveFormRepository Instance
        {
            get
            {
                if (WaveFormRepository.instance == null)
                    WaveFormRepository.instance = new WaveFormRepository();
                return WaveFormRepository.instance;
            }
        }

        public void Refresh()
        {
            this.waveForms.Clear();
            ObservableCollection<WaveFormInfo> newItems = WaveFormRepository.GetWaveFormInfoItems();
            foreach (WaveFormInfo item in newItems)
            {
                this.waveForms.Add(item);
            }
        }

        public ObservableCollection<WaveFormInfo> WaveForms
        {
            get
            {
                if (this.waveForms == null)
                    this.waveForms = WaveFormRepository.GetWaveFormInfoItems();
                return this.waveForms;
            }
        }

        public WaveFormInfo FindByName(string name)
        {
            var items = from item in this.WaveForms
                        where item.Name == name
                        select item;
            return items.First();
        }

        static ObservableCollection<WaveFormInfo> GetWaveFormInfoItems()
        {
            ObservableCollection<WaveFormInfo> items = new ObservableCollection<WaveFormInfo>();

            WaveFormInfo item = new WaveFormInfo();
            item.Name = "sin";
            item.WaveForm = new SineWaveForm();
            items.Add(item);

            item = new WaveFormInfo();
            item.Name = "saw";
            item.WaveForm = new SawWaveForm();
            items.Add(item);

            item = new WaveFormInfo();
            item.Name = "sqr";
            item.WaveForm = new SquareWaveForm();
            items.Add(item);

            item = new WaveFormInfo();
            item.Name = "tri";
            item.WaveForm = new TriangleWaveForm();
            items.Add(item);

            item = new WaveFormInfo();
            item.Name = "noise";
            item.WaveForm = new NoiseWaveForm();
            items.Add(item);

            return items;
        }

        //public static ObservableCollection<WaveFormInfo> GetCustomWaveForms()
        //{
        //    ObservableCollection<WaveFormInfo> newItems = new ObservableCollection<WaveFormInfo>();

        //    using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
        //    {
        //        string extension = "*.ksw";
        //        string[] files = storage.GetFileNames(extension);

        //        for (int i = 0; i < files.Length; i++)
        //        {
        //            WaveFormInfo info = ReadCustomWaveForm(files[i], storage);
        //            SetWaveFormInfoImageSource(info, files[i], storage);
        //            newItems.Add(info);
        //        }
        //    }
        //    return newItems;
        //}

        //static void SetWaveFormInfoImageSource(WaveFormInfo info, string fileName, IsolatedStorageFile storage)
        //{
        //    BitmapImage img = new BitmapImage();
        //    string imageFileName = fileName.Replace(".ksw", ".jpg");

        //    using (IsolatedStorageFileStream imageStream =
        //         storage.OpenFile(imageFileName, FileMode.Open))
        //    {
        //        img.SetSource(imageStream);
        //        info.ImageSource = img;
        //    }
        //}

        //static WaveFormInfo ReadCustomWaveForm(string fileName, IsolatedStorageFile storage)
        //{
        //    using (IsolatedStorageFileStream stream = storage.OpenFile(fileName, FileMode.Open))
        //    {
        //        using (StreamReader reader = new StreamReader(stream))
        //        {
        //            string jsonData = reader.ReadToEnd();
        //            using (MemoryStream ms = new MemoryStream(
        //                Encoding.Unicode.GetBytes(jsonData)))
        //            {
        //                DataContractJsonSerializer serializer =
        //                        new DataContractJsonSerializer(typeof(CustomWaveForm));
        //                CustomWaveForm waveForm = (CustomWaveForm)serializer.ReadObject(ms);
        //                WaveFormInfo info = new WaveFormInfo();
        //                info.WaveForm = waveForm;
        //                if (string.IsNullOrEmpty(waveForm.Name))
        //                    info.Name = "unknown";
        //                else
        //                    info.Name = waveForm.Name;
        //                return info;
        //            }

        //        }
        //    }

        //}

        //public static void WriteCustomWaveForm(IsolatedStorageFile storage, CustomWaveForm waveForm, WriteableBitmap waveFormImage)
        //{
        //    string fileName = waveForm.Name + ".ksw";

        //    bool exists = storage.FileExists(fileName);
        //    IsolatedStorageFileStream stream;
        //    if (exists)
        //        stream = storage.OpenFile(fileName, FileMode.Truncate);
        //    else
        //        stream = storage.CreateFile(fileName);


        //        string jsonString;

        //        using (MemoryStream ms = new MemoryStream())
        //        {
        //            DataContractJsonSerializer serializer =
        //                   new DataContractJsonSerializer(waveForm.GetType());
        //            serializer.WriteObject(ms, waveForm);
        //            ms.Position = 0;
        //            using (StreamReader reader = new StreamReader(ms))
        //            {
        //                jsonString = reader.ReadToEnd();
        //            }
        //        }

        //        using (StreamWriter writer = new StreamWriter(stream))
        //        {
        //            writer.Write(jsonString);
        //            writer.Close();
        //        }
        //        SaveWaveformImage(storage, waveFormImage, waveForm);

        //        stream.Dispose();
        //}

        //static void SaveWaveformImage(IsolatedStorageFile storage, WriteableBitmap bitmap, CustomWaveForm waveForm)
        //{
        //    string imagePath = waveForm.Name + ".jpg";
        //    using (IsolatedStorageFileStream fs = storage.OpenFile(imagePath, FileMode.OpenOrCreate))
        //    {

        //        //Convert the Image to pass into FJCore
        //        int width = bitmap.PixelWidth;
        //        int height = bitmap.PixelHeight;
        //        int bands = 3;

        //        byte[][,] raster = new byte[bands][,];

        //        for (int i = 0; i < bands; i++)
        //        {
        //            raster[i] = new byte[width, height];
        //        }

        //        for (int row = 0; row < height; row++)
        //        {
        //            for (int column = 0; column < width; column++)
        //            {
        //                int pixel = bitmap.Pixels[width * row + column];
        //                raster[0][column, row] = (byte)(pixel >> 16);
        //                raster[1][column, row] = (byte)(pixel >> 8);
        //                raster[2][column, row] = (byte)pixel;
        //            }
        //        }

        //        ColorModel model = new ColorModel { colorspace = ColorSpace.RGB };

        //        FluxJpeg.Core.Image img = new FluxJpeg.Core.Image(model, raster);

        //        //Encode the Image as a JPEG
        //        MemoryStream stream = new MemoryStream();
        //        JpegEncoder encoder = new JpegEncoder(img, 100, stream);

        //        encoder.Encode();

        //        //Move back to the start of the stream
        //        stream.Seek(0, SeekOrigin.Begin);

        //        //Get the Bytes and write them to the stream
        //        byte[] binaryData = new Byte[stream.Length];
        //        long bytesRead = stream.Read(binaryData, 0, (int)stream.Length);

        //        fs.Write(binaryData, 0, binaryData.Length);
        //    }
        //}


    }
}
